import React, { Component, Fragment } from 'react';
import { Row, Col, Popover, Button, Icon, Modal } from 'antd';
import { WeaLocaleProvider, WeaInput, WeaTree, WeaSelect, WeaDialog, WeaTab, message } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import cloneDeep from 'lodash/cloneDeep';

const confirm = Modal.confirm;
const { getLabel } = WeaLocaleProvider;

@inject('correspondFieldStore')
@observer
export default class CorrespondFieldComp extends Component {
  constructor(props) {
    super(props);
    this.prefix = 'odoc-difBranchCata';
    this.delete = this.delete.bind(this);
  }

  componentDidMount() {
    const { correspondFieldStore, unitId } = this.props;
    correspondFieldStore.getTreeData(unitId);
  }

  componentDidUpdate() {
    if (this.needFocus) {
      if (this.refs.xxx.refs.input) {
        this.refs.xxx.focus();
        this.needFocus = false;
      }
    }
  }

  componentWillUnmount() {
    const { correspondFieldStore } = this.props;
    correspondFieldStore.init();
  }

  render() {
    const { correspondFieldStore } = this.props;
    const { datas, expandedKeys, onExpand, checkKeys, onCheck, onDrag, count, addToLast, onDatasChange, nodeBrotherShow, setMobxState,
      onDegrade, degradeNode, degradeBrotherId, onSelect } = correspondFieldStore;
    return (
      <div className="odoc-difBranchCata">
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9wrdh1`} className="fieldTable-Title">

          <div className="firstColumn">
            <div className="gutter-box">
              {/* <WeaCheckbox
                style={{marginLeft:'14px',marginRight:'4px',backgroundColor: '#e9f5ff'}}
                onChange={value => selectAll(value)}
              /> */}
              <span>{getLabel('514162', 'XML节点名称')}</span>
            </div>
          </div>

          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3qv7ms`} className="secendColumn" >
            <div>{getLabel('22217', '字段值')}</div>
          </Col>

          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@h7d5vi`} className="thirdColumn" />

        </Row>

        <WeaTree ecId={`${this && this.props && this.props.ecId || ''}_WeaTree@c5kdzu`}
          rowKey="id"
          datas={toJS(datas)}
          // draggable  //不能拖动的原因是组件库那边拖动有很多bug  没有解决 还有拖动抛出的数据太少 很多需要的数据没有办法获取到
          expandedKeys={toJS(expandedKeys)}
          onExpand={(expandedKey, data) => onExpand(expandedKey, data)}
          checkedKeys={toJS(checkKeys)}
          onCheck={onCheck}
          checkable={true}
          renderNode={item => this.getTitle(item)}
          onDrag={(dragNode, targetNode, data) => onDrag(dragNode, targetNode, data)}
          key={count}
          addToLast={addToLast}
          onAdd={(value, node) => this.onAdd(value, node)}
          ref="xxx"
          onDatasChange={data => onDatasChange(data)}
          loadAll={true}
          // checkStrictly={true}
          onSelect={(ids, nodeids, nodes, event) => onSelect(ids, nodeids, nodes, event)}
        />

        <WeaDialog
          ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@syml0v`}
          onCancel={() => setMobxState({ nodeBrotherShow: false, degradeBrotherId: '' })}
          title={getLabel('513216', '选择降级节点的父节点')}
          visible={nodeBrotherShow}
          style={{ width: 600, height: 400 }}
          hasScroll
          buttons={[
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nbs3kj@ok`} type="primary" disabled={degradeBrotherId === ''} onClick={() => onDegrade(toJS(degradeNode), degradeBrotherId, toJS(checkKeys))}>{getLabel('33703', '确认')}</Button>,
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mfusto@cancel`} type="primary" onClick={() => setMobxState({ nodeBrotherShow: false, searchsBaseValue: '', degradeBrotherId: '' })}>{getLabel('31129', '取消')}</Button>,
          ]}
        >
          {this.getBrotherNode()}
        </WeaDialog>
      </div>
    );
  }

  getTitle(item) {
    const { correspondFieldStore } = this.props;
    const { valueChange, exchangeFieldOpsData, fieldTypeOpsData } = correspondFieldStore;
    const { prefix } = this;

    return (
      <div className={`${prefix}-TreeNode`} style={{ width: `calc(700px - ${item.hierarchy * 18}px)` }} >
        <div className={`${prefix}-TreeNode-left`}
          style={{ width: `calc(340px - ${item.hierarchy * 18}px)` }}
        >
          <span className={`${prefix}-TreeNode-left-name`} title={item.title} onClick={e => this.treeClick(e)}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@emjr6q`}
              // style={{ width: 200 }}
              value={item.name}
              customBlur={value => valueChange('name', value, item.id)}
              viewAttr={3}
            />
          </span>
        </div>
        {!(item.children && item.children.length > 0) &&
          <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@7xg7rl`}>
            <div className={`${prefix}-TreeNode-right`} onClick={e => this.treeClick(e)}>
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@df7m8p`}
                hasBorder
                options={toJS(fieldTypeOpsData)}
                value={item.field}
                onChange={value => valueChange('field', value, item.id)}
              />
            </div>

            <div className={`${prefix}-TreeNode-fieldValue`}>
              {
                item.field == '1' &&
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@vlwgv3`}
                  hasBorder
                  options={toJS(exchangeFieldOpsData)}
                  value={item.fieldSelectValue}
                  onChange={value => valueChange('fieldSelectValue', value, item.id)}
                  viewAttr={3}
                />
              }

              {
                item.field == '2' &&
                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@hz3rhp`}
                  style={{ width: 200 }}
                  value={item.fieldInputValue}
                  customBlur={value => valueChange('fieldInputValue', value, item.id)}
                  viewAttr={3}
                />
              }
            </div>
          </Fragment>
        }

        <div className={`${prefix}-TreeNode-opeart`} >
          {this.getOperatContent(item)}
        </div>
      </div>
    );
  }

  getOperatContent(item) {
    const content1 = (
      <div className="menuContent1">
        <div onClick={() => this.addNode(item)} title={getLabel('513211', '添加子节点')}>{getLabel('513211', '添加子节点')}</div>
        <div onClick={() => this.topNode(item)} title={getLabel('513212', '上方添加节点')}>{getLabel('513212', '上方添加节点')}</div>
        <div onClick={() => this.bottomNode(item)} title={getLabel('513213', '下方添加节点')}>{getLabel('513213', '下方添加节点')}</div>
      </div>
    );
    const content2 = (
      <div className="menuContent2">
        <div onClick={() => this.shiftUp(item)} title={getLabel('15084', '上移')}>{getLabel('15084', '上移')}</div>
        <div onClick={() => this.shiftDown(item)} title={getLabel('15085', '下移')}>{getLabel('15085', '下移')}</div>
        <div onClick={() => this.upgrade(item)} title={getLabel('17530', '升级')}>{getLabel('17530', '升级')}</div>
        <div onClick={() => this.degrade(item)} title={getLabel('17531', '降级')}>{getLabel('17531', '降级')}</div>
      </div>
    );
    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@uuxdtm`}>
        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@lntvnh`} placement="bottom" content={content1} trigger="hover">
          <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@88bdtx`} type="plus" />
        </Popover>
        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@f2poif`} placement="bottom" content={content2} trigger="hover">
          <i className="icon-coms02-coms-Row-operation" />
        </Popover>
        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@aem34z`} type="cross" onClick={() => this.delete(item)} title={getLabel('91', '删除')} />
      </Fragment>
    );
  }

  // 添加子节点
  addNode(item) {
    this.refs.xxx.opsHandler(item, { type: 'add' });
  }

  // 上方添加节点
  topNode(item) {
    this.addSiblingNode(item, true);
  }

  // 下方添加节点
  bottomNode(item) {
    this.addSiblingNode(item, false);
  }

  // 上移
  shiftUp(item) {
    const { correspondFieldStore } = this.props;
    const { moveSiblingNode, isFirstNode } = correspondFieldStore;
    if (!isFirstNode(item.id, true).includes(true)) {
      moveSiblingNode(item.id);
    } else {
      message.warning(getLabel('514378', '该节点不能上移'));
    }
  }

  // 下移
  shiftDown(item) {
    const { correspondFieldStore } = this.props;
    const { moveSiblingNode, isFirstNode } = correspondFieldStore;
    if (!isFirstNode(item.id, false).includes(true)) {
      moveSiblingNode(item.id, false);
    } else {
      message.warning(getLabel('514379', '该节点不能下移'));
    }
  }

  // 升级
  upgrade(item) {
    const { correspondFieldStore } = this.props;
    const { onUpgrade } = correspondFieldStore;
    onUpgrade(item);
  }

  // 降级
  degrade(item) {
    const { correspondFieldStore } = this.props;
    const { getBrotherNode } = correspondFieldStore;
    getBrotherNode(item);
  }

  delete(item) {
    this.refs.xxx.opsHandler(item, { type: 'delete' });
  }

  onAdd(v, item) {
    return new Promise((resolve) => {
      const hierarchy = item ? 1 + Number(item.hierarchy) : this.addBrotherNodeHierarchy;
      const newId = Math.random().toString(36).substr(2);
      const data = {
        name: v,
        id: newId,
        isParent: true,
        nodeid: newId,
        canClick: true,
        hierarchy,
        field: '1',
        fieldSelectValue: '',
        fieldInputValue: '',
        isadd: true,
        pid: item ? item.id : '',
      };
      const regExp = new RegExp(/^\d/);
      if (regExp.test(v)) {
        message.warning(getLabel('515209', 'XML节点名称不能以数字开头'));
        this.needFocus = true;
      }
      this.addBrotherNodeHierarchy = 0;
      resolve(data);
    });
  }

  changeTreeDatas(data, id, target, upward = true) {
    for (let i in data) {
      if (data[i].id == id) {
        upward && data.splice(Number(i), 0, target);
        !upward && data.splice(Number(i) + 1, 0, target);
        return;
      }
      if (data[i].children && data[i].children.length > 0) {
        this.changeTreeDatas(data[i].children, id, target, upward);
      }
    }
  }

  addSiblingNode(item, upward) {
    const { correspondFieldStore } = this.props;
    const { datas } = this.refs.xxx.state;
    const target = {
      name: '',
      displayType: 'add',
      // isRoot: true,
      treeKey: 'add',
      hierarchy: item.hierarchy,
      pid: item.pid,
    };
    this.refs.xxx.treeMap.add = cloneDeep(target);
    this.changeTreeDatas(datas, item.id, target, upward);
    this.addBrotherNodeHierarchy = item.hierarchy;
    correspondFieldStore.onDatasChange(datas);
    this.refs.xxx.setState({ datas }, () => {
      this.needFocus = true;
    });
  }

  getBrotherNode() {
    const { correspondFieldStore } = this.props;
    const { nodeBrother, onSelectDegradeParentNode, searchsBaseValue, setMobxState, exchangeFieldOpsData } = correspondFieldStore;
    let options = [];
    toJS(nodeBrother).map((item) => {
      let name = '';
      if (item.isadd) {
        if (item.field == '1') {
          const arr = toJS(exchangeFieldOpsData).find(i => i.key == item.fieldSelectValue);
          if (arr) {
            name = arr.showname;
          } else {
            name = '';
          }
        } else if (item.field == '2') {
          name = item.fieldInputValue;
        }
      }
      const showname = (item.fieldName || name) ? `${item.name} (  ${item.fieldName || name}  ) ` : `${item.name}`;
      if (showname.toLocaleLowerCase().includes(searchsBaseValue.toLocaleLowerCase())) {
        options.push({
          key: item.id,
          showname,
          selected: false,
        });
      }
    });
    return (
      <div className="odocExchange-unitSet-fieldseting-dialog">
        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@df8cnm`}
          searchType={['base']}
          onSearch={v => setMobxState({ searchsBaseValue: v })}
          searchsBaseValue={searchsBaseValue}
        />
        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@gq94ni`}
          style={{ height: '344px', width: '100%', overflow: 'scroll' }}
          options={options}
          detailtype={3}
          supportCancel
          onChange={v => onSelectDegradeParentNode(v)}
        />
      </div>
    );
  }

  // 批量删除 外抛方法
  batchDelete() {
    const { correspondFieldStore } = this.props;
    const { batchDelete } = correspondFieldStore;
    confirm({
      title: getLabel('131329', '信息确认'),
      content: getLabel('515853', '确定要删除选择的节点吗?'),
      onOk() {
        batchDelete();
      },
      onCancel() { },
    });
  }

  // 批量降级 外抛方法
  batchDegrade() {
    const { correspondFieldStore } = this.props;
    const { checkIsSameParent } = correspondFieldStore;
    checkIsSameParent();
  }


  // 批量升级 外抛方法
  batchUpgrade() {
    // const { correspondFieldStore } = this.props;
    // const { batchUpgrade } = correspondFieldStore;
    // checkIsSameParent();
  }

  // 保存树数据 外抛方法
  saveTreeData() {
    const { correspondFieldStore, unitId } = this.props;
    const { onSaveTreeData } = correspondFieldStore;
    onSaveTreeData(unitId);
  }

  treeClick(e) {
    e.preventDefault();
    e.stopPropagation();
  }
}
